<template>
  <div class="layout-container" :class="{ old: elder }">
    <div class="layout-section layout-section2">
      <top-header :show-elder="false" :auth-check="true" @setElder="setElderByChild"></top-header>

      <van-collapse v-for="(data,index) in list" v-model="activeNames" @change="showEntIndex(index)"
                    class="ques-list title_list" size="large" :key="index">
        <van-collapse-item :name="topIdx" v-for="(lst,topIdx) in list" :key="topIdx">
          <template #title>
            <img class="imgtit" src="@/assets/jzy/icons_2.png" alt=""/>
            <span>{{ lst.unitName }}</span>
          </template>
          <van-checkbox-group v-model="checked">
            <van-cell is-link v-for="(subItem,subIdx) in lst.indexs" :key="subItem.CODE" >
              <template slot="title">
                <van-checkbox shape="square" :name="subItem.CODE" :disabled="subItem.LIST.length === 0"
                              @click="restItem(topIdx,subIdx,subItem.LIST)">
                  {{ subItem.NAME }}
                </van-checkbox>
              </template>
              <template slot="default">
                <div @click="selItem(topIdx,subIdx,subItem.LIST)">
                  {{ getItemMsg(topIdx,subIdx,subItem.LIST) }}
                </div>
              </template>
            </van-cell>
          </van-checkbox-group>

          <div class="item_btn">
            <!--van-button plain type="primary" @click="reGain(index)">重新获取</van-button-->
            <van-button plain type="info" size="small" @click="showArchive(index, 'view')">查看档案</van-button>&nbsp;&nbsp;
            <van-button plain type="info" size="small" @click="showArchive(index, 'download')">下载到本地</van-button>&nbsp;&nbsp;
          </div>
        </van-collapse-item>
      </van-collapse>

      <!--列表载入错误信息-->
      <div class="home-error-msg" v-if="error.show">{{ error.msg }}</div>

      <div class="item_btn" style="margin-bottom: 20px;">
        <van-button plain type="warning" size="small" @click="goHome">返回首页</van-button>&nbsp;&nbsp;
        <van-button plain type="warning" size="small" @click="goList">返回列表</van-button>
      </div>

      <footer-right></footer-right>
    </div>

    <footer-nav :active-index="-1"></footer-nav>

    <!--pdf预览-->
    <van-dialog v-model="pdfContainer.show" title="查看企业档案" :show-confirm-button="false" :show-cancel-button="false">
      <pdf :src="pdfContainer.url" :page="pdfContainer.curPage" @num-pages="pdfContainer.totalPage - $event"></pdf>
      <div style="margin: 10px;">
        <div style="float:left; line-height: 35px; height: 35px; ">{{ pdfContainer.curPage }}/{{ pdfContainer.totalPage }}</div>
        <div style="float: right;">
          <van-button type="warning" size="small" @click="prePage">上一页</van-button>
          <van-button type="warning" size="small" @click="nextPage">下一页</van-button>
          <van-button type="danger" size="small" @click="pdfContainer.show=false">关闭窗口</van-button>
        </div>
      </div>
    </van-dialog>

    <!--材料选择-->
    <van-dialog v-model="items.show" title="选择打印材料" style="max-height: 600px; overflow-y: auto;"
                :show-confirm-button="true" :show-cancel-button="true" @confirm="confirmSel">
      <van-cell-group>
        <van-cell v-for="(item, index) in items.list" clickable :key="item.filename"
                  :title="'【'+item.filedate+'】' + item.itemname" @click="item.checked=!item.checked">
          <van-checkbox :name="item" slot="right-icon" v-model="item.checked"/>
        </van-cell>
      </van-cell-group>
    </van-dialog>
  </div>
</template>

<script>
import pdf from "vue-pdf";
import FooterNav from "@/components/footerNav";
import FooterRight from "@/components/footerRight";
import TopHeader from "@/components/topHeader";

import {strUtils, ajaxUtils, eraqConstants} from "@/utils/lwUtils";
import {entsList, indexList, apiGetArchive} from '@/api/applyDetail'

export default {
  components: {FooterRight, FooterNav, TopHeader, pdf},
  data() {
    return {
      activeNames: [],
      elder: false,
      list: [],
      checked: [],
      error: {
        show: true, msg: ""
      },
      pdfContainer: {
        show: false, url: "", pages: "", curPage: 1, totalPage: 0
      },
      items: {
        show: false, topIdx: 0, subIdx: 0, list: []
      },
      loadding: null,
    }
  },
  created() {
    let unid = this.$route.query.unid;
    if (strUtils.isEmpty(unid)) {
      this.$eraqDlg.warning("参数有误，查询企业清单失败");
      return;
    }
    this.listEnts(unid);
  },
  methods: {
    //页面载入时，加载查询企业清单
    listEnts: function (unid) {
      entsList(unid).then(res => {
        if (ajaxUtils.isFail(res.code, res.msg)) {
          this.list = [];
          this.activeNames = [];
          this.error.show = true;
          this.error.msg = strUtils.isEmpty(res.msg) ? "加载查询企业清单异常" : res.msg;
          return;
        }
        this.error.show = false;
        this.list = res.data;
        this.activeNames = [];
        this.list.forEach(ents => {
          this.$set(ents, "loaded", false);
          this.$set(ents, "indexs", []);
          this.$set(ents, "checked", []);
        });
      }).catch(() => {
        this.list = [];
        this.activeNames = [];
        this.error.show = true;
        this.error.msg = "加载查询企业清单异常";
      });
    },
    //加载所选企业内档目录
    showEntIndex: function (index) {
      //当前为关闭事件，不执行操作
      if (this.activeNames.includes(index)) {
        return;
      }
      var ents = this.list[index];

      //已加载档案目录，不执行操作
      if (ents.loaded) {
        return;
      }
      //加载企业档案目录
      indexList(ents.unid).then(res => {
        let list = res.data;

        //对接口返回的数据进行初始化，添加选中状态
        list.forEach(p => {
          p.CHECKED = false;
          p.LIST.forEach(c => {
            c.checked = false;
          })
        });

        this.$set(ents, "loaded", true);
        this.$set(ents, "indexs", list);
      }).catch(() => {
        this.$eraqDlg.error("加载企业档案目录异常");
        this.$set(ents, "loaded", true);
        this.$set(ents, "indexs", []);
      });
    },
    //重新获取
    reGain: function (index) {
      var ents = this.list[index];
    },
    goList: function () {
      this.$router.push({path: '/list'});
    },
    goHome: function () {
      this.$router.push({path: '/home'});
    },
    //查看档案-主入口
    showArchive: function (index,flag) {
      let unids = [];
      this.list[index].indexs.forEach(p=>{p.LIST.forEach(c=>{if (c.checked) {unids.push(c.unid)}})});
      if (unids.length === 0) {
        this.$eraqDlg.warning("请先选择档案目录");
        return;
      }
      apiGetArchive(this.list[index].unid, unids.join(","), "2").then(res => {
        if (ajaxUtils.checkFail(res.code, res.msg)) {
          return;
        }

        //获得档案文件地址
        //archiveUrl = "https://qyda.tzscjg.cn:8090/eraq-api/profile/help/manual.pdf";
        if (flag === "download") {
          this.downloadPdf(res.data.filePathObs);
          return;
        }
        this.showPdf(res.data.filePathObs);
      }).catch(() => {
        if (this.loadding !== null) {
          this.loadding.clear();
          this.loadding = null;
        }
        this.$eraqDlg.error("生成档案异常，请稍侯再试");
      });
    },
    //查看档案-在线预览
    showPdf: function (fileUrl) {
      this.loadding = this.$eraqDlg.showLoading("正在加载档案");
      this.pdfContainer.url = pdf.createLoadingTask(fileUrl);
      this.pdfContainer.url.promise.then(pdf => {
        this.$nextTick(() => {
          this.pdfContainer.totalPage = pdf.numPages;
          this.pdfContainer.curPage = 1;
        });
        if (this.loadding !== null) {
          this.loadding.clear();
          this.loadding = null;
        }
        this.pdfContainer.show = true;
      }).catch(()=>{
        if (this.loadding !== null) {
          this.loadding.clear();
          this.loadding = null;
        }
        this.$eraqDlg.error("档案加载异常");
      });
    },
    //查看档案-下载到本地
    downloadPdf: function (fileUrl) {
      ZWJSBridge.saveImage({
        url: fileUrl
      }).then((result) => {
        console.log(result);
      }).catch((error) => {
        console.log(error);
      });
    },

    //在线预览PDF翻页
    prePage: function () {
      let page = this.pdfContainer.curPage;
      page = page > 1 ? page - 1 : this.pdfContainer.totalPage;
      this.pdfContainer.curPage = page;
    },
    nextPage: function () {
      let page = this.pdfContainer.curPage;
      page = page < this.pdfContainer.totalPage ? page + 1 : 1;
      this.pdfContainer.curPage = page;
    },

    //子组件调用方法，设置老年模式
    setElderByChild: function (elder) {
      this.elder = elder;
    },

    //获取选择的档案资料清单数量
    getItemMsg: function (topIdx, subIdx, list) {
      let total = list.length;
      let seled = 0;
      list.forEach(ay => { seled += ay.checked ? 1 : 0; });
      return "已选" + seled + "份/共" + total + "份";
    },
    //选择材料清单-打开选择窗口
    selItem: function (topIdx, subIdx, list) {
      if (list.length === 0 || !this.checked.includes(this.list[topIdx].indexs[subIdx].CODE)) {
        return;
      }
      this.items.topIdx = topIdx;
      this.items.subIdx = subIdx;
      this.items.show = true;
      this.items.list = list;
    },
    //选择材料清单-确定选择
    confirmSel: function () {
      this.list[this.items.topIdx].indexs[this.items.subIdx].list = this.items.list;
    },

    //选择档案目录时，对选择的材料清单目录进行重置（选中时，自动选中第一项；取消选择时，对所有选中项进行清理）
    restItem: function (topIdx,subIdx,list) {
      if (list.length === 0) {
        return;
      }
      if (this.checked.includes(this.list[topIdx].indexs[subIdx].CODE)) {
        this.list[topIdx].indexs[subIdx].LIST[0].checked = true;
      } else {
        this.list[topIdx].indexs[subIdx].LIST.forEach(item=>{
          item.checked = false;
        });
      }
    },
  },
  mounted() {
  }
}
</script>

<style lang='scss' scoped>
@import "src/css/home";
@import "src/css/jzy";
</style>
